﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using ICSharpCode.SharpZipLib;
using System.Reflection;
using ICSharpCode.SharpZipLib.Zip;
using ICSharpCode.SharpZipLib.Core;

namespace FileWatcher
{
    class Program
    {
        public static Assembly ass = Assembly.GetExecutingAssembly();
        public static String tempFolderPath = System.IO.Path.GetDirectoryName(ass.Location) + @"\\tmp";

        static void Main(string[] args)
        {
            String path = System.Configuration.ConfigurationSettings.AppSettings["path"].ToString();   //"C:\Users\Haseeb\Documents\FileWatcher";
            CreateFileWatcher(@path);
        }

        public static void CreateFileWatcher(string path)
        {
            FileSystemWatcher watcher = new FileSystemWatcher();
            watcher.Path = path;

            watcher.IncludeSubdirectories = true;
            watcher.NotifyFilter = NotifyFilters.FileName;

            // Add event handlers.
            watcher.Changed += new FileSystemEventHandler(OnChanged);
            watcher.Created += new FileSystemEventHandler(OnChanged);
            watcher.Deleted += new FileSystemEventHandler(OnChanged);
            watcher.Renamed += new RenamedEventHandler(OnRenamed);

            watcher.EnableRaisingEvents = true;
            while (Console.Read() != 'q') ;
        }

        // Define the event handlers.
        private static void OnChanged(object source, FileSystemEventArgs e)
        {
            // Specify what is done when a file is changed, created, or deleted.
            Console.WriteLine(DateTime.Now.ToString() + "\n" + e.FullPath + "\n" + e.ChangeType.ToString().ToUpper());
            Console.WriteLine("----------");
        }
        private static void OnRenamed(object source, RenamedEventArgs e)
        {
            // Specify what is done when a file is renamed.
            Console.WriteLine("{0} File {1}\nRENAMED TO\n{2}", DateTime.Now.ToString() , e.OldFullPath, e.FullPath);
            Console.WriteLine("----------");

            String changed_file = e.FullPath;
            String temp_path = tempFolderPath + "\\temp" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".zip";

            FileInfo file = new FileInfo(e.FullPath);
            string aa = file.Extension;
            if (file.Extension.Equals(".tpqx"))
            {
                try
                {
                    File.Copy(changed_file, temp_path);
                    ExtractZipFile(temp_path, tempFolderPath);
                }
                catch (Exception ex)
                {

                }
            }

            
        }

        public static void ExtractZipFile(String ArchiveFile, String Destination)
        {
            ZipFile zip_file = null;
            try
            {
                FileStream file_stream = File.OpenRead(ArchiveFile);
                zip_file = new ZipFile(file_stream);

                foreach (ZipEntry zipEntry in zip_file)
                {
                    if (!zipEntry.IsFile)
                        continue;           // Ignore directories

                    String entryFileName = zipEntry.Name;
                    entryFileName = new FileInfo(ArchiveFile).Name + ".xml";
                    // to remove the folder from the entry:- entryFileName = Path.GetFileName(entryFileName);
                    // Optionally match entrynames against a selection list here to skip as desired.
                    // The unpacked length is available in the zipEntry.Size property.

                    byte[] buffer = new byte[4096];     // 4K is optimum
                    Stream zipStream = zip_file.GetInputStream(zipEntry);

                    // Manipulate the output filename here as desired.
                    String fullZipToPath = Path.Combine(Destination, entryFileName);
                    string directoryName = Path.GetDirectoryName(fullZipToPath);
                    if (directoryName.Length > 0)
                        Directory.CreateDirectory(directoryName);

                    // Unzip file in buffered chunks. This is just as fast as unpacking to a buffer the full size
                    // of the file, but does not waste memory.
                    // The "using" will close the stream even if an exception occurs.
                    using (FileStream streamWriter = File.Create(fullZipToPath))
                        StreamUtils.Copy(zipStream, streamWriter, buffer);
                }
            }
            finally
            {
                if (zip_file != null)
                {
                    zip_file.IsStreamOwner = true; // Makes close also shut the underlying stream
                    zip_file.Close(); // Ensure we release resources
                }
            }
        }

    }
}
